//
//  WZTileView.swift
//  WZApp
//
//  Created by evol on 2018/6/8.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import Kingfisher

class ELTileView: UIView {
    
    let defaultSize:CGFloat = 256.0
    
    private var tileSize: CGSize {
        get{
            return CGSize(width: defaultSize * APP_RATE, height: defaultSize * APP_RATE)
        }
    }
    
    override class var layerClass: AnyClass {
        get {
            return CATiledLayer.self
        }
    }
    
    init() {
        super.init(frame: .zero)
        let layer = self.layer as! CATiledLayer
        let scaledTileSize = tileSize.applying(CGAffineTransform(scaleX: self.contentScaleFactor, y: self.contentScaleFactor));
        layer.contentsScale = UIScreen.main.scale
        layer.tileSize = scaledTileSize
        layer.levelsOfDetailBias = 3
        layer.levelsOfDetail = 1
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("not init")
    }
    
    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        let scale = (context?.ctm.a)!/UIScreen.main.scale
        let col = rect.minX * scale/tileSize.width
        let row = rect.minY * scale/tileSize.width
        let imageString = String(format: "http://api.zjart.net.cn/tiles/ios/wuzhen1.0/days/_wz_days_%.0fx_%.0f_%.0f.jpg", scale,row,col)
        var image = UIImage.imageFromCache(imageString)
        if image == nil {
            let data = try? Data(contentsOf: URL(string: imageString)!)
            guard data != nil else {
                print(imageString,"文件不存在")
                return
            }
            image = UIImage(data: data!)
        }
        image?.draw(in: rect)
    }

}
